<?php
/**
 * Author: lf
 * Blog: https://blog.szdma.com
 * Email: job@szdma.com
 * Created at: 2016-04-14 21:53.
 */

namespace backend\grid;

use Closure;
use kartik\grid\CheckboxColumn as kartikCheckboxColumn;
use yii\helpers\Html;
use yii\helpers\Json;

/**
 * {@inheritdoc}
 */
class CheckboxColumn extends kartikCheckboxColumn
{
    public $width = '10px';

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        if (!isset($this->headerOptions['width'])) {
            $this->headerOptions['width'] = $this->width;
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function renderHeaderCellContent()
    {
        if (null !== $this->header || !$this->multiple) {
            return parent::renderHeaderCellContent();
        } else {
            static $i = 1;
            $unique = uniqid().$i;
            ++$i;
            $for              = 'inlineCheckbox'.$unique;
            $options['id']    = $for;
            $options['class'] = 'i-checks';

            return Html::checkbox($this->getHeaderCheckBoxName(), false, $options);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index)
    {
        if ($this->checkboxOptions instanceof Closure) {
            $options = call_user_func($this->checkboxOptions, $model, $key, $index, $this);
        } else {
            $options = $this->checkboxOptions;
        }

        if (!isset($options['value'])) {
            $options['value'] = is_array($key) ? Json::encode($key) : $key;
        }

        if (null !== $this->cssClass) {
            Html::addCssClass($options, $this->cssClass);
        }

        static $i = 1;
        $unique = uniqid().$i;
        ++$i;
        $for              = 'inlineCheckbox'.$unique;
        $options['id']    = $for;
        $options['class'] = 'i-checks';

        return Html::checkbox($this->getHeaderCheckBoxName(), false, $options);
    }
}
